package jmind.core.util;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 延时执行线程池
 * @author weibo-xie
 * 2012-4-11
 */
public class DelayTaskExecutor {

    private DelayTaskExecutor() {
    }

    private static final DelayTaskExecutor rte = new DelayTaskExecutor();
    //  single thread  同时执行的task 只有一个   Executors.newScheduledThreadPool(20);
    private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    public static DelayTaskExecutor getInstance() {

        return rte;
    }

    public void runTask(Runnable task) {
        executor.execute(task);
    }

    /**
     * 延时多少分钟执行
     * @param command
     * @param delay
     */
    public void schedule(Runnable command, long delay) {
        executor.schedule(command, delay, TimeUnit.MINUTES);
    }

    /**
     * @param command 要执行的任务
     * @param delay 从现在开始延迟执行的时间
     * @param unit 延迟参数的时间单位 
     */
    public void schedule(Runnable command, long delay, TimeUnit unit) {
        executor.schedule(command, delay, unit);
    }

    static int t = 1;
    static int k = 1000;

    public static void main(String[] args) {
        System.out.println(new Date());

        for (int i = 0; i < 10; i++) {
            System.out.println("thread " + i);
            Runnable command = new Runnable() {

                @Override
                public void run() {

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println(++t + "-->" + System.currentTimeMillis());
                }

            };
            DelayTaskExecutor.rte.runTask(command);
        }
    }

}
